import {
  Route,
  Routes,
  Navigate,
  useNavigate,
  useLocation,
  useParams,
  useSearchParams,
} from "react-router-dom";
import { Suspense, useEffect } from "react";
import routes from "./routes";
import { Skeleton, Toast } from "antd-mobile";

import store from "../store";
import action from "../store/action";

function isCheckLogin(path) {
  let checkList = ["/personal", "/store", "/update"];
  const {
    user: { info },
  } = store.getState();
  // 如果没有信息  并且要去的是这些地址
  return !info && checkList.includes(path);
}
isCheckLogin();
function Element(props) {
  const { component: Component, name, meta, path } = props;
  const { title = "知乎日报" } = meta || {};
  // 修改页面标题
  document.title = title;
  const isShow = !isCheckLogin(path);

  useEffect(() => {
    // 没有user信息或者不是去store不会走下面逻辑
    if (isShow) return;
    (async () => {
      let infoAction = await action.user.getUserInfo();
      let info = infoAction.info;

      if (info && path === "/login") return;
      if (!info) {
        Toast.show({
          icon: "fail",
          content: "请先登录",
        });
        console.log(path, "path");
        navigate("/login?to=" + path, {
          replace: true,
        });
        return;
      }
      store.dispatch(infoAction);
    })();
  });
  const [usp] = useSearchParams();
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  return (
    <Component
      usp={usp}
      navigate={navigate}
      params={params}
      location={location}
      name={name}
      meta={meta}
    />
  );
}

function RouterView() {
  return (
    <Suspense
      fallback={
        <>
          <Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={5} animated />
        </>
      }
    >
      <Routes>
        {routes.map((route, index) => {
          const { path } = route;
          return (
            <Route key={index} path={path} element={<Element {...route} />} />
          );
        })}
      </Routes>
    </Suspense>
  );
}

export default RouterView;
